﻿using System.Collections.Specialized;

namespace Azalea.ORMap
{
    public class SqlUpdate : ISqlUpdate
    {
        private readonly CommandBuilder _cmdBuilder;
        private readonly NameValueCollection _fieldParams = new NameValueCollection();
        private string _tableName;

        public SqlUpdate(CommandBuilder cmdBuilder)
        {
            _cmdBuilder = cmdBuilder;
        }

        #region ISqlUpdate Members

        public ISqlUpdate Table(string tableName)
        {
            _tableName = tableName;

            return this;
        }

        public ISqlUpdate Set(string field, object value)
        {
            string parameterName = _cmdBuilder.AddParameter(_tableName, field, value, false);

            _fieldParams.Add(field, parameterName);

            return this;
        }

        public ISqlWhere Where()
        {
            GenerateSql();

            return new SqlWhere(_cmdBuilder, _tableName);
        }

        public ICommandBuilder Done()
        {
            GenerateSql();

            return _cmdBuilder;
        }

        #endregion

        private void GenerateSql()
        {
            _cmdBuilder._sqlBuilder.Append("update ")
                .Append(_cmdBuilder.QuotingKeyword(_tableName))
                .Append(" set ");

            bool commaNeeded = false;
            foreach (string field in _fieldParams.Keys)
            {
                if (commaNeeded)
                {
                    _cmdBuilder._sqlBuilder.Append(",");
                }

                _cmdBuilder._sqlBuilder.Append(_cmdBuilder.QuotingKeyword(field))
                    .Append("=")
                    .Append(_fieldParams[field]);

                commaNeeded = true;
            }
        }
    }
}